package hhs.scannerapp;

import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Point;

import android.util.Log;

public class Frame2Model {
	private static final float MATCH_ERR = 0.00001f;
	static List<EdgeModel> toModel(List<EdgeFrame> frames) {
		//Determine a base pixel height
		EdgeFrame init = frames.get(0);
		double btmY = 0;
		double topY = 1000;
		for(Point p : init.leftPoints){
			if(p.y > btmY)
				btmY = p.y;
			if(p.y < topY)
				topY = p.y;
		}
		for(Point p : init.rightPoints){
			if(p.y > btmY)
				btmY = p.y;
			if(p.y < topY)
				topY = p.y;
		}
		double baseY = (btmY+topY)/2;
		
		//Pair leftPoints with rightPoints at one half rotation after		
		final float HALF_ROT = 0.5f;
		List<List<Point>> sortedRight = new ArrayList<List<Point>>();
		List<List<Point>> sortedLeft = new ArrayList<List<Point>>();
		for(int i = 0; i < frames.size(); i++) {
			float leftT = frames.get(i).t;
			for(int j = 0; j < frames.size(); j++) {
				float diffT = (float)Math.abs(frames.get(j).t-leftT);
				//Log.e("OpenCVTest", "t: "+diffT);
				if(Math.abs(diffT - HALF_ROT) <= MATCH_ERR) {
					sortedLeft.add(frames.get(i).leftPoints);
					sortedRight.add(frames.get(j).rightPoints);
				}
			}
		}
		
		List<EdgeModel> models = new ArrayList<EdgeModel>();
		Log.e("OpenCVTest", "F: "+frames.size());
		Log.e("OpenCVTest", "L: "+sortedRight.size());
		//Find EdgeModel
		for(int i = 0; i < sortedLeft.size(); i++) {
			EdgeModel em = new EdgeModel();
			em.edges = new ArrayList<EdgeModel.EdgePoint>();
			List<Point> leftPoints = sortedLeft.get(i);
			List<Point> rightPoints = sortedRight.get(i); 
			em.rot = frames.get(i).t;
			
			for(int j = 0; j < leftPoints.size(); j++) {
				EdgeModel.EdgePoint e = em.new EdgePoint();
				e.h = baseY-leftPoints.get(j).y;
				e.r = rightPoints.get(j).x-leftPoints.get(j).x;
				e.r/=2;
				em.edges.add(e);
			}
			models.add(em);
		}
		
		Log.e("OpenCVTest", "Made model");
		
		return models;
	}
}
